package com.wanpinghui.supplier.product;

import android.content.Intent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.wanpinghui.supplier.R;
import com.wanpinghui.supplier.common.BaseWebActivity;
import com.wanpinghui.supplier.message.MessageP2PActivity;
import com.wanpinghui.supplier.message.nim.NimManager;
import com.wanpinghui.supplier.oauth.LoginActivity;
import com.wanpinghui.wphlibrary.WPHSdk;
import com.wanpinghui.wphlibrary.common.UrlConstants;
import com.wanpinghui.wphlibrary.common.toast.ToastManager;
import com.wanpinghui.wphlibrary.model.oauth.OAuthService;
import com.wanpinghui.wphlibrary.model.oauth.bean.UserBean;
import com.wanpinghui.wphlibrary.model.order.bean.SingleOrderItem;
import com.wanpinghui.wphlibrary.model.product.CartCountChangeListener;
import com.wanpinghui.wphlibrary.model.product.ProductService;
import com.wanpinghui.wphlibrary.model.product.bean.AddCartParamsBean;
import com.wanpinghui.wphlibrary.model.product.bean.OrderCreateParams;
import com.wanpinghui.wphlibrary.model.product.bean.ProductBean;
import com.wanpinghui.wphlibrary.model.product.bean.ProductFormatBean;
import com.wanpinghui.wphlibrary.photovideo.bean.UploadFileBean;
import com.wanpinghui.wphlibrary.webapp.BaseJsInvokeListener;
import com.wanpinghui.wphlibrary.webapp.JSMethod;
import com.wanpinghui.wphlibrary.webapp.WPHWebView;
import com.wanpinghui.wphlibrary.widgets.ThrottleButton;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

import retrofit.callback.YRequestCallback;

/***
 * 功能描述:
 * 作者:qiujialiu
 * 时间:2017/12/25
 ***/
@ContentView(R.layout.layout_activity_product_detail)
public class ProductDetailActivity extends BaseWebActivity implements CartCountChangeListener {
    public static final int REQUEST_SELECT_PHOTO = 101;
    private static final int CLIP_PHOTO = 102;
    @ViewInject(R.id.web_view)
    private WPHWebView wphWebView;
    @ViewInject(R.id.rl_loading)
    private RelativeLayout layoutLoading;
    @ViewInject(R.id.tv_error)
    private TextView textViewError;
    @ViewInject(R.id.ll_connect)
    private LinearLayout layoutConnect;
    @ViewInject(R.id.btn_add_cart)
    private ThrottleButton buttonAdd;
    @ViewInject(R.id.btn_buy_now)
    private ThrottleButton buttonBuy;

    private int buyerId;
    private int sellerId;
    private UserBean userBean;
    private ArrayList<UploadFileBean> photoList;
    private ProductBean mProdcutBean;
    private FormatManager formatManager;
    private int productId;

    private String url = UrlConstants.WebAppURL + "/pro_info.html?pid=";


    @Override
    public String getName() {
        return null;
    }

    @Override
    public boolean isBar() {
        return false;
    }

    @Override
    public void initViews() {
        WPHSdk.addCartCountChangeListener(this);
        formatManager = new FormatManager(ProductDetailActivity.this);
        if (getIntent() != null) {
            productId = getIntent().getIntExtra("id", 0);
            sellerId = getIntent().getIntExtra("seller_id", 0);
            buyerId = getIntent().getIntExtra("buy_id", 0);
        }

        url = url + productId + "&sid="+sellerId+"&token="+WPHSdk.getService(OAuthService.class).getToken();
        wphWebView.addJsMethod(new JSMethod(UrlConstants.URL, new BaseJsInvokeListener(){
            @Override
            public void onLoadProduct(ProductBean productBean) {
                mProdcutBean = productBean;
                sellerId = mProdcutBean.getSupplier_id();
            }

            @Override
            public void tokenInvalid() {
                NimManager.getInstance().logout();
                startActivity(new Intent(ProductDetailActivity.this, LoginActivity.class));
                finish();
            }

            @Override
            public void onSelectFormat(ProductBean productBean) {
                if (mProdcutBean != null) {
                    formatManager.setDatas(mProdcutBean);
                    if (userBean != null && sellerId == userBean.getUser().getIntId()) {
                        formatManager.setSeller(true);
                    } else {
                        formatManager.setSeller(false);
                    }
                    formatManager.setType(1);
                    formatManager.show(findViewById(R.id.root_view));
                    formatManager.setSureClick(new FormatManager.SureClick() {
                        @Override
                        public void onAddToCart(ProductBean productBean) {
                            addToCart(productBean);
                        }

                        @Override
                        public void onCreateOrder(ProductBean bean) {
                            createOrder(bean);
                        }

                        @Override
                        public void onSure(ProductBean bean) {

                        }
                    });
                }
            }

            @Override
            public void goShoppingCart() {
                super.goShoppingCart();
                startActivity(new Intent(ProductDetailActivity.this, CartListActivity.class));
            }

            @Override
            public void goBack() {
                finish();
            }
        }));
//        if (getIntent() != null) {
//            buyerId = getIntent().getIntExtra("user_id",0);
//            sellerId = getIntent().getIntExtra("seller_id",0);
//        }
        userBean = WPHSdk.getService(OAuthService.class).getUserInfo(null);
        if (userBean != null) {
            if (buyerId == 0) {
                buyerId = userBean.getUser().getIntId();
            }
            if (sellerId == userBean.getUser().getIntId()) {
                buttonBuy.setText("代他采购");
            } else if (buyerId == userBean.getUser().getIntId()) {
                buttonBuy.setText("立即采购");
            }
        }
    }

    private void createOrder(ProductBean bean) {
        if (bean == null || sellerId == 0) {
            return;
        }
        final OrderCreateParams params = new OrderCreateParams(buyerId, sellerId);
        List<OrderCreateParams.ItemParams> itemParamsList = new ArrayList<>();
        if (bean.getFormatList() != null && bean.getFormatList().size() > 0) {
            for (ProductFormatBean formatBean : bean.getFormatList()) {
                if (formatBean.getCount() > 0) {
                    OrderCreateParams.ItemParams itemParams = new OrderCreateParams.ItemParams(null, formatBean.getProduct_desc_id(), formatBean.getId(), formatBean.getCount()
                    );
                    itemParamsList.add(itemParams);
                }
            }
        } else if (bean.getSelectCount() > 0) {
            OrderCreateParams.ItemParams itemParams = new OrderCreateParams.ItemParams(
                    null, bean.getProduct_desc_id(), null, bean.getSelectCount()
            );
            itemParamsList.add(itemParams);
        }
        if (itemParamsList != null && itemParamsList.size() > 0) {
            params.setItemList(itemParamsList);
            WPHSdk.getService(ProductService.class).createOrder(params, new YRequestCallback<SingleOrderItem>() {
                @Override
                public void onSuccess(SingleOrderItem var1) {
                    mProdcutBean.resetSelectCountToZero();
                    if (params.getBuyer_id() == userBean.getUser().getIntId()) {
                        MessageP2PActivity.start(ProductDetailActivity.this, params.getSeller_id(), new Gson().toJson(var1));
                    } else {
                        MessageP2PActivity.start(ProductDetailActivity.this, params.getBuyer_id(), new Gson().toJson(var1));
                    }
                }

                @Override
                public void onFailed(int var1, String message) {
                    showWarningText(message);
                }

                @Override
                public void onException(Throwable var1) {
                    showWarningText("出错了[" + var1.toString() + "]");
                    var1.printStackTrace();
                }
            });
        }
    }

    private void addToCart(ProductBean productBean) {
        List<AddCartParamsBean> list = new ArrayList<>();
        if (productBean.getFormatCount() == 0) {
            list.add(new AddCartParamsBean(productBean.getProduct_desc_id(), productBean.getCount(), buyerId));
        } else {
            for (ProductFormatBean formatBean : productBean.getFormatList()) {
                list.add(new AddCartParamsBean(productBean.getProduct_desc_id(), formatBean.getId(), formatBean.getCount(), buyerId));
            }
        }
        if (buyerId == Integer.parseInt(userBean.getUser().getId())) {
            WPHSdk.getService(ProductService.class)
                    .addToCart(list, new YRequestCallback() {
                        @Override
                        public void onSuccess(Object var1) {
                            ToastManager.getInstance().showToast("已成功加入购物车");
                            mProdcutBean.resetSelectCountToZero();
                        }

                        @Override
                        public void onFailed(int var1, String message) {
                            showWarningText(message);
                        }

                        @Override
                        public void onException(Throwable var1) {

                        }
                    });
        } else {
            WPHSdk.getService(ProductService.class)
                    .addBuyerCart(list, new YRequestCallback() {
                        @Override
                        public void onSuccess(Object var1) {
                            ToastManager.getInstance().showToast("已成功加入购物车");
                            mProdcutBean.resetSelectCountToZero();
                        }

                        @Override
                        public void onFailed(int var1, String message) {
                            showWarningText(message);
                        }

                        @Override
                        public void onException(Throwable var1) {

                        }
                    });
        }
    }

    @Override
    public void bindEvents() {
        layoutConnect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (userBean != null && sellerId == userBean.getUser().getIntId()) {
                    showWarningText("您已是该产品供应商");
                } else {
                    MessageP2PActivity.start(ProductDetailActivity.this, "" + sellerId);
                }
            }
        });

        buttonAdd.setOnThrottleClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mProdcutBean != null) {
                    formatManager.setDatas(mProdcutBean);
                    if (userBean != null && sellerId == userBean.getUser().getIntId()) {
                        formatManager.setSeller(true);
                    } else {
                        formatManager.setSeller(false);
                    }
                    formatManager.setType(0);
                    formatManager.show(findViewById(R.id.root_view));
                    formatManager.setSureClick(new FormatManager.SureClick() {
                        @Override
                        public void onAddToCart(ProductBean productBean) {
                        }

                        @Override
                        public void onCreateOrder(ProductBean bean) {
                        }

                        @Override
                        public void onSure(ProductBean bean) {
                            addToCart(bean);
                        }
                    });
                }
            }
        });

        buttonBuy.setOnThrottleClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mProdcutBean != null) {
                    formatManager.setDatas(mProdcutBean);
                    if (userBean != null && sellerId == userBean.getUser().getIntId()) {
                        formatManager.setSeller(true);
                    } else {
                        formatManager.setSeller(false);
                    }
                    formatManager.setType(0);
                    formatManager.show(findViewById(R.id.root_view));
                    formatManager.setSureClick(new FormatManager.SureClick() {
                        @Override
                        public void onAddToCart(ProductBean productBean) {
                        }

                        @Override
                        public void onCreateOrder(ProductBean bean) {
                        }

                        @Override
                        public void onSure(ProductBean bean) {
                            createOrder(bean);
                        }
                    });
                }
            }
        });
    }

    @Override
    protected WPHWebView getWebView() {
        return wphWebView;
    }

    @Override
    public void initData() {
        super.initData();
        layoutLoading.setVisibility(View.VISIBLE);
        textViewError.setVisibility(View.GONE);
        wphWebView.loadUrl(url);
        WPHSdk.getService(ProductService.class).getCartCount(false, null);
    }

    @Override
    protected void onLoadError() {
        layoutLoading.setVisibility(View.GONE);
        textViewError.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onLoadSuccess() {
        layoutLoading.setVisibility(View.GONE);
        textViewError.setVisibility(View.GONE);
    }

    @Override
    protected void onLoadStart() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onChange(int count) {
        if (wphWebView != null) {
            wphWebView.setCartCount(count);
        }
    }
}
